<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useBookStore } from '@/stores/book';
import { useUserStore } from '@/stores/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import UserAvatar from '@/components/UserAvatar.vue';

const router = useRouter();
const bookStore = useBookStore();
const userStore = useUserStore();

// 数据
const books = ref([]);
const total = ref(0);
const loading = ref(false);
const searchTitle = ref('');
const selectedCategory = ref('');

// 分页
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  sortBy: 'id'
});

// 计算属性
const categories = computed(() => bookStore.categories);

// 加载图书列表
const loadBooks = async () => {
  loading.value = true;
  try {
    const { currentPage, pageSize, sortBy } = pagination.value;
    const data = await bookStore.fetchBooks(currentPage, pageSize, sortBy);
    books.value = data.results || [];
    total.value = data.count || 0;
  } catch (error) {
    console.error('加载图书列表失败:', error);
    ElMessage.error('加载图书列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索图书
const searchBooks = async () => {
  loading.value = true;
  pagination.value.currentPage = 1; // 重置分页
  try {
    // 支持同时按标题和分类搜索
    if (searchTitle.value && selectedCategory.value) {
      // 同时有标题和分类条件
      const titleResult = await bookStore.searchByTitle(searchTitle.value);
      const categoryResult = await bookStore.fetchBooksByCategory(selectedCategory.value);
      
      // 取交集
      const titleBooks = Array.isArray(titleResult) ? titleResult : (titleResult?.data || []);
      const categoryBooks = Array.isArray(categoryResult) ? categoryResult : (categoryResult?.data || []);
      
      const intersection = titleBooks.filter(titleBook => 
        categoryBooks.some(categoryBook => categoryBook.id === titleBook.id)
      );
      
      books.value = intersection;
      total.value = intersection.length;
    } else if (selectedCategory.value) {
      // 只有分类条件
      await filterByCategory();
      return;
    } else if (searchTitle.value) {
      // 只有标题条件
      const result = await bookStore.searchByTitle(searchTitle.value);
      console.log('搜索结果:', result);
      if (result && Array.isArray(result)) {
        books.value = result;
        total.value = result.length;
      } else if (result && result.data) {
        const data = result.data;
        books.value = data.results || data;
        total.value = data.count || (Array.isArray(data) ? data.length : 0);
      }
    } else {
      // 如果没有搜索条件，加载所有图书
      await loadBooks();
    }
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error('搜索失败: ' + (error.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 按分类筛选
const filterByCategory = async () => {
  if (!selectedCategory.value) {
    loadBooks();
    return;
  }
  
  loading.value = true;
  try {
    console.log('按分类筛选:', selectedCategory.value);
    
    // 使用后端分类筛选API
    const result = await bookStore.fetchBooksByCategory(selectedCategory.value);
    console.log('分类筛选结果:', result);
    
    if (result && Array.isArray(result)) {
      books.value = result;
      total.value = result.length;
    } else if (result && result.data) {
      const data = result.data;
      books.value = data.results || data;
      total.value = data.count || (Array.isArray(data) ? data.length : 0);
    } else {
      books.value = [];
      total.value = 0;
    }
    
    // 重置分页
    pagination.value.currentPage = 1;
  } catch (error) {
    console.error('按分类筛选失败:', error);
    ElMessage.error('按分类筛选失败: ' + (error.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 处理分类选择变化
const handleCategoryChange = (value) => {
  console.log('分类选择变化:', value);
  selectedCategory.value = value;
};

// 清空搜索
const clearSearch = () => {
  searchTitle.value = '';
  selectedCategory.value = '';
  pagination.value.currentPage = 1;
  loadBooks();
};

// 处理分页变化
const handlePageChange = (page) => {
  pagination.value.currentPage = page;
  loadBooks();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  loadBooks();
};

// 新增图书
const addBook = () => {
  router.push('/books/create');
};

// 编辑图书
const editBook = (row) => {
  router.push(`/books/edit/${row.id}`);
};

// 删除图书
const deleteBook = (row) => {
  ElMessageBox.confirm(`确定要删除《${row.title}》吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await bookStore.removeBook(row.id);
      ElMessage.success('删除成功');
      loadBooks();
    } catch (error) {
      console.error('删除图书失败:', error);
      ElMessage.error('删除图书失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 处理图片URL
const handleImageUrl = (url) => {
  if (!url) return '';
  // 如果是相对路径，添加基础URL
  if (!url.startsWith('http')) {
    return `${import.meta.env.VITE_API_BASE_URL || ''}${url}`;
  }
  return url;
};

onMounted(() => {
  // 初始化用户信息
  userStore.initUserInfo();
  
  // 检查是否有有效的token和用户信息
  const currentUser = userStore.getCurrentUsername();
  const token = localStorage.getItem('token');
  if (!token || currentUser === '未知用户') {
    console.warn('检测到无效会话，自动登出');
    userStore.logout().then(() => {
      router.push('/login');
    });
    return;
  }
  
  loadBooks();
});
</script>

<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>图书管理</h1>
      <div class="header-right">
        <el-button type="primary" @click="addBook">
          <el-icon><Plus /></el-icon>
          添加图书
        </el-button>
      </div>
    </div>
    
    <el-card shadow="hover" class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="图书标题">
          <el-input v-model="searchTitle" placeholder="请输入图书标题" clearable />
        </el-form-item>
        <el-form-item label="图书分类">
          <el-select 
            v-model="selectedCategory" 
            placeholder="请选择分类" 
            clearable
            style="width: 200px"
            @change="handleCategoryChange">
            <el-option 
              v-for="category in categories" 
              :key="category" 
              :label="category" 
              :value="category">
              {{ category }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBooks">搜索</el-button>
          <el-button @click="clearSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card shadow="hover" class="table-card">
      <el-table
        v-loading="loading"
        :data="books"
        border
        style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" min-width="120" align="center" />
        <el-table-column prop="category" label="分类" width="120" align="center" />
        <el-table-column prop="price" label="价格" width="100" align="center">
          <template #default="scope">
            ¥{{ scope.row.price ? scope.row.price.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.gmtCreate || scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="editBook(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteBook(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
/* 统一页面容器样式 - Author: Logan.Li */
.page-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f5f5;
}

/* 统一页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
}

/* 统一卡片样式 */
.search-card, .table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
